/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var moment = require("moment");
var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');
var formidable = require('formidable');
var fs = require('fs');
var moment = require("moment");


var qdArticleController = {
    getQdArticlePage: function (req, res) {
        co(function () {
            var page = parseInt(req.query.page);
            var params = {};
            var paramT = {};
            //模糊查询
            if (req.query.title != undefined) {
                params["title"] = { "$like": "%" + req.query.title + "%" };
            }
            if (req.query.qrCode != undefined) {
                params["qrCode"] = req.query.qrCode;
            }
            paramT["where"] = params;
            paramT["order"] = [["code", 'ASC']];
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            seq.qdWjArticleModule.findAndCountAll(paramT).then(function (result) {
                res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
            });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })

    },
    getQdArticleById: function (req, res) {
        co(function () {
            var paramT = {};
            paramT.include = [{ model: seq.jwytAuthModule, attributes: ["url"] }]
            paramT.where = req.params;
            seq.qdWjArticleModule.findOne(paramT).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '查询成功', 'result': qdMeet });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })
    },
    addQdArticle: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/qdArticle";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });

                    if (files.pic != null && files.pic.name != "") {
                        var imgType = files.pic.name.split(".");
                        files.pic.name = "qrImage_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                        fs.renameSync(files.pic.path, form.uploadDir + "/" + files.pic.name);
                        fields["pic"] = files.pic.name;
                    }
                    var type = util.getUUID().replace(/-/g, "");
                    var params = {};
                    params.type = type;
                    fields.type = type;
                    fields.url = util.getAuthUrl + "&type=" + type;
                    if (fields.wjId != undefined && fields.wjId != null && fields.wjId != "") {
                        params.filed1 = fields.wjId;
                        delete fields.wjId;
                    }
                    params.url = fields.authUrl;
                    params.createTime = util.getNowTime();
                    params.id = util.getUUID();
                    fields.id = util.getUUID();
                    fields.createTime = util.getNowTime();
                    delete fields.authUrl;
                    seq.qdWjArticleModule.create(fields).then(function (qdMeet) {
                        seq.jwytAuthModule.create(params).then(function (quthAdd) {
                            res.redirect(util.getIP() + "qdQr/qdArticleList.html?qrCode=" + fields.qrCode);
                        })
                    })

                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })
    },
    updateQdArticle: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/qdArticle";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });

                    if (files.pic != null && files.pic.name != "") {

                        var imgType = files.pic.name.split(".");
                        files.pic.name = "qrImage_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                        fs.renameSync(files.pic.path, form.uploadDir + "/" + files.pic.name);
                        fields["pic"] = files.pic.name;
                    }
                    var params = {};
                    var type = fields.type;
                    params.url = fields.authUrl;
                    delete fields.authUrl;
                    seq.qdWjArticleModule.update(fields, { where: req.params }).then(function (qdMeet) {
                        seq.jwytAuthModule.update(params, { where: { type: type } }).then(function (quthAdd) {
                            res.redirect(util.getIP() + "qdQr/qdArticleList.html?qrCode=" + fields.qrCode);
                        })
                    })

                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })
    },
    deleteQdArticle: function (req, res) {
        co(function () {
            var params = req.query.params;
            var arr = params.split(",");
            var paramT = [arr];
            seq.qdWjArticleModule.destroy({ where: { id: paramT } }).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '删除成功' });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    }
}
module.exports = qdArticleController;